package com.uphone.kingmall.activity;

import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.SizeUtils;
import com.china.zhuoyue.R;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.personal.ShopComplainActivity;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.CatsListBean;
import com.uphone.kingmall.bean.ShopInfoBean;
import com.uphone.kingmall.fragment.ShopAllGoodsFragment;
import com.uphone.kingmall.fragment.ShopCommendFragment;
import com.uphone.kingmall.fragment.business_area.ShopDetailsFragment;
import com.uphone.kingmall.fragment.business_area.ShopHomeFragment;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyScrollView0;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.RatingBar;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.utils.intent.IntentUtils;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
//import io.rong.imkit.RongIM;
//import io.rong.imlib.model.CSCustomServiceInfo;

/**
 * author : SuMeng
 * e-mail : 986335838@qq.com
 * time   : 2019/02/28
 * desc   : 店铺详情页面
 */
public class ShopDetailActivity extends BaseActivity {

    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.iv_shop_icon)
    ImageView ivShopIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.rb_shop)
    RatingBar rbShop;
    @BindView(R.id.tv_shop_collect)
    TextView tvShopCollect;
    @BindView(R.id.tv_shop_complain)
    TextView tvShopComplain;
    @BindView(R.id.stl_shop)
    CommonTabLayout stlShop;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.nsv_shop_details)
    MyScrollView0 nestedScrollView;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.fl_shop)
    FrameLayout frameLayout;
    @BindView(R.id.rl_center)
    RelativeLayout rlCenter;
    @BindView(R.id.tv_status_bar)
    TextView tvStatusBar;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_goods_count)
    TextView tv_goods_count;
    @BindView(R.id.tv_total_money)
    TextView tv_total_money;
    private ShopInfoBean bean;

    @IntentData
    int id = -1;

    private String[] titles = new String[]{"推荐宝贝", "全部商品", "店铺详情"};
    private Fragment[] fragments = new Fragment[3];//{ShopHomeFragment.newInstance(), ShopGoodsListFragment.newInstance(), ShopDetailsFragment.newInstance()};

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_shop_detail;
    }

    //    1.机器人
//    2.不能添加数据
//    3.没有规格顶上去
//
    @Override
    public void initView() {
        setImmersionBar();
        showFragment(0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            nestedScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    int height = SizeUtils.dp2px(40);
                    int alpha;
                    float scale;
                    if (scrollY <= height) {
                        scale = (float) scrollY / height;
                        alpha = (int) (255 * scale);
                        // 随着滑动距离改变透明度
                        llTitle.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
                    } else {
                        // 防止频繁重复设置相同的值影响性能
                        alpha = 255;
                        llTitle.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
                    }
                }
            });
        }
    }

    @Override
    public void initData() {
        ArrayList<CustomTabEntity> customTabEntities = new ArrayList<>();
        for (final String title : titles) {
            CustomTabEntity customTabEntity = new CustomTabEntity() {
                @Override
                public String getTabTitle() {
                    return title;
                }

                @Override
                public int getTabSelectedIcon() {
                    return 0;
                }

                @Override
                public int getTabUnselectedIcon() {
                    return 0;
                }
            };
            customTabEntities.add(customTabEntity);
        }
        stlShop.setTabData(customTabEntities);
        stlShop.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                showFragment(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        // 加载网络数据
        HttpParams params = new HttpParams();
        params.put("shopId", id);
        //获取商品详情
        OkGoUtils.progressRequest(MyUrl.getShopInfo, this, params, new onNormalRequestListener() {


            @Override
            public void onSuccess(String body, int code) {
                bean = GsonUtils.getGson().fromJson(body, ShopInfoBean.class);
                loadData();

            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getShopGoodsCats();
    }

    private void loadData() {
        if (bean != null && bean.getShop() != null) {
            ShopInfoBean.ShopBean shop = bean.getShop();
            GlideUtils.getInstance().loadNormalImage(this, shop.getShopBgImg(), ivTitle);
            GlideUtils.getInstance().loadCornerImage(this, shop.getShopHeadImg(), SizeUtils.dp2px(4), ivShopIcon);
            tvShopName.setText(shop.getShopName());
            if (shop.getCollectState() != null && shop.getCollectState() == 1) {
                //已关注
                tvShopCollect.setSelected(true);
                tvShopCollect.setText("已关注");
            } else {
                tvShopCollect.setSelected(false);
                tvShopCollect.setText("关注");
            }
            if (shop.getShopScore() != null) {
                rbShop.setStar(shop.getShopScore());
            }
            if (ShopHomeFragment.getFragment() != null) {
                ShopHomeFragment.getFragment().setUrl(shop.getShopDesc());
            }
            if (ShopDetailsFragment.getFragment() != null) {
                ShopDetailsFragment.getFragment().loadData(shop);
            }
        }
    }

    private void showFragment(int position) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        if (fragments[position] == null) {
            switch (position) {
                case 0:
                    ShopCommendFragment fragment = ShopCommendFragment.newInstance(id);
                    fragment.setAddGoodsListener(new ShopCommendFragment.AddGoodsListener() {
                        @Override
                        public void onAddClick() {
                            getShopGoodsCats();
                        }
                    });
                    fragments[position] = fragment;
                    break;
                case 1:
                    ShopAllGoodsFragment shopAllGoodsFragment = ShopAllGoodsFragment.newInstance(id);
                    shopAllGoodsFragment.setAddGoodsListener(new ShopAllGoodsFragment.AddGoodsListener() {
                        @Override
                        public void onAddClick() {
                            getShopGoodsCats();
                        }
                    });
                    fragments[position] = shopAllGoodsFragment;
                    break;
                case 2:
                    fragments[position] = ShopDetailsFragment.newInstance();
                    if (bean != null && bean.getShop() != null) {
                        ShopDetailsFragment.getFragment().loadData(bean.getShop());
                    }
                    break;
            }
            fragmentTransaction.add(R.id.fl_shop, fragments[position]);
        }
        hideFragment(fragmentTransaction);
        fragmentTransaction.show(fragments[position]);
        fragmentTransaction.commit();
        if (position == 0) {
            ivTitle.setFocusable(true);

            ivTitle.setFocusableInTouchMode(true);
        }
    }

    //隐藏所有的fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (fragments[0] != null) {
            transaction.hide(fragments[0]);
        }
        if (fragments[1] != null) {
            transaction.hide(fragments[1]);
        }
        if (fragments[2] != null) {
            transaction.hide(fragments[2]);
        }
    }

    @OnClick({R.id.tv_shop_collect, R.id.tv_shop_complain, R.id.iv_back, R.id.tv_search, R.id.tv_call, R.id.tv_go_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_shop_collect://关注
                if (TextUtils.equals("关注", tvShopCollect.getText().toString().trim())) {
                    // 关注店铺
                    CollectShop();
                } else {
                    // 取消关注
                    unCollectShop();
                }
                break;
            case R.id.tv_shop_complain://投诉店铺
                if (CommonUtil.checkLogin()) {
                    IntentUtils.getInstance().with(this, ShopComplainActivity.class)
                            .putInt(ConstansUtils.ID, id).start();
                }
                break;
            case R.id.tv_search://搜索
                IntentUtils.getInstance().with(this, SearchGoodsListActivity.class).
                        putInt(ConstansUtils.ID, id).start();
                break;
            case R.id.tv_call:
//                if (bean != null && bean.getShop() != null && !TextUtils.isEmpty(bean.getShop().getShopPhone())) {
//                    DialogUtil.showCallDialog(this, bean.getShop().getShopPhone());
//                } else {
//                    //联系商家
//                    CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                    final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                    RongIM.getInstance().startCustomerServiceChat(this, ConstansUtils.CSCustomServiceId, "", csInfo);
//                }
                break;
            case R.id.tv_go_pay://进入购物车
                if (CommonUtil.checkLogin()) {
                    CommonUtil.startIntent(this, ShoppingCartActivity.class);
                }
                break;
            default:
                break;
        }
    }

    private void unCollectShop() {
        HttpParams params = new HttpParams();
        params.put("shopId", id);
        OkGoUtils.progressRequest(MyUrl.cancleCollectShop, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    bean.getShop().setCollectState(0);
                    tvShopCollect.setText("关注");
                    tvShopCollect.setSelected(false);
                    ToastUtils.showShortToast(ShopDetailActivity.this, "已取消");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void CollectShop() {
        HttpParams params = new HttpParams();
        params.put("shopId", id);
        OkGoUtils.progressRequest(MyUrl.collectShop, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    bean.getShop().setCollectState(1);
                    tvShopCollect.setText("已关注");
                    tvShopCollect.setSelected(true);
                    ToastUtils.showShortToast(ShopDetailActivity.this, "关注成功");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    /**
     * 查询商铺分类
     */
    private void getShopGoodsCats() {
        HttpParams params = new HttpParams();
        params.put("shopId", id);
        OkGoUtils.normalRequest(MyUrl.getShopGoodsCats, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                CatsListBean bean = GsonUtils.getGson().fromJson(body, CatsListBean.class);
                if (bean.getCode() == 0 && bean.getCats() != null && bean.getCats().size() > 0) {
                    int shopCarGoodsCatNum = 0;
                    double totalMoney = 0.0;
                    for (CatsListBean.CatsBean catsBean : bean.getCats()) {
                        shopCarGoodsCatNum += catsBean.shopCarGoodsCatNum;
                        totalMoney += catsBean.totalPrice;
                    }
                    tv_total_money.setText(String.format(Locale.CHINA, "￥%.2f", totalMoney));
                    tv_goods_count.setText(String.valueOf(shopCarGoodsCatNum));
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

}
